<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Compute Cells</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style>
        nav.clean {
            background: none;
            box-shadow: none;
        }

        .breadcrumb:before {
            color: rgba(0, 0, 0, 0.7);
        }

        .breadcrumb, .breadcrumb:last-child {
            color: rgba(0, 0, 0, 1);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="section">
        <nav class="clean">
            <div class="nav-wrapper">
                <div class="col s12" id="breadcrumb-path">
                    <a href="/compute_pools.html" class="breadcrumb" id="pool-caption"></a>
                </div>
            </div>
        </nav>
    </div>
    <div class="divider"></div>
    <div class="section">
        <div class="row">
            <div class="col m3">
                <a class="waves-effect waves-light blue-grey lighten-2 btn" id="add-button"><i class="material-icons left">add</i></a>
            </div>
            <div class="col m3 push-m6" id="autofresh">
            </div>
        </div>
    </div>
    <div class="section" id="cell_list">
    </div>
    <div class="modal" id="modal_confirm">
        <div class="modal-content">
            <h4>Remove Confirm</h4>
            <p id="confirm_content"></p>
        </div>
        <div class="modal-footer">
            <a href="#" class="modal-close waves-effect waves-green btn-flat">No</a>
            <a href="#" class="modal-close waves-effect waves-green btn-flat" id="confirm_link">Yes</a>
        </div>
    </div>
    <div class="modal" id="migrate-modal">
        <!--hide model -->
        <div class="modal-content">
            <h4>Migrate Instance</h4>
            <div class="row">
              <p id="migrate-content">
              </p>
            </div>
            <div class="row">
              <div class="input-field col m4">
                  <select name="migrate-target" id="migrate-target-options">
                  </select>
                  <label>Target Cell</label>
              </div>
            </div>
        </div>
        <div class="modal-footer">
            <a href="#" class="modal-close waves-effect waves-green btn-flat"></a>
            <a href="#" class="modal-close waves-effect waves-green btn-flat" id="migrate-confirm-link"></a>
        </div>
    </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>
    N.ValidateSession();
    var texts = N.GetTexts();
    $('#add-button').append(texts.get(N.TagAdd));
    $('#pool-caption').text(texts.get(N.TagComputePool));
    $('.modal-footer > a:first-child').text(texts.get(N.TagCancel));
    $('.modal-footer > a:last-child').text(texts.get(N.TagConfirm));

    //auto fresh switch
    $('#autofresh').append(
      $('<span>').text(texts.get(N.TagAutoFresh))
    ).append(
      $('<div>').addClass('switch').append(
        $('<label>').append(texts.get(N.TagOff)).append(
          $('<input>').attr('type', 'checkbox').attr('onclick', 'onAutoFreshSwitched()').attr('id', 'switch-autofresh').prop('checked', true)
        ).append(
          $('<span>').addClass('lever')
        ).append(texts.get(N.TagOn))
      )
    )

    var poolName;

    M.AutoInit();

    function parseQueryString(){
      var url = window.location.search;
      var queryParams = new Map();
      var queryString = url.substring( url.indexOf('?') + 1 );
      if (0 === queryString.length){
        return queryParams;
      }
      var values = queryString.split("&");
      values.forEach((value) => {
        var p = value.split('=');
        queryParams.set(p[0], p[1]);
      });
      return queryParams;
    }

    function refresh(){
      loadCells();
    }

    function outputMessage(message){
      $('#cell_list').empty().append(
        $('<div>').addClass('center').append(
          $('<span>').text(message)
        )
      );
    }

    function loadCells(){
      $.getJSON(
        '/compute_pool_cells/' + poolName,
        function(result){
          if (0 != result['error_code']) {
            outputMessage(result['message']);
            return;
          }
          $('#cell_list').empty();
          if (!result['data']){
            outputMessage('no compute cell available');
            return
          }
          if (0 == result['data'].length){
            outputMessage('no compute cell available');
            return;
          }
          var container = $('<div>').addClass('row');
          var table = $('<table>').append(
            $('<thead>').append(
              $('<tr>').append(
                $('<td>').text(texts.get(N.TagCell))
              ).append(
                $('<td>').text(texts.get(N.TagAddress))
              ).append(
                $('<td>').text(texts.get(N.TagAlive))
              ).append(
                $('<td>').text(texts.get(N.TagStatus))
              ).append($('<td>'))
            )
          );
          result['data'].forEach((cell) => {
            var content = $('<tr>');
            content.append(
              $('<td>').text(cell['name'])
            ).append(
              $('<td>').text(cell['address'])
            );
            //alive
            if (cell['alive']){
              content.append(
                $('<td>').append(
                  $('<i>').addClass('material-icons green-text darken-2 tooltipped').attr('data-position', 'top').
                    attr('data-tooltip', texts.get(N.TagOnline)).text('wifi')
                )
              );
            }else{
              content.append(
                $('<td>').append(
                  $('<i>').addClass('material-icons blue-grey-text tooltipped').attr('data-position', 'top').
                    attr('data-tooltip', texts.get(N.TagOffline)).text('signal_wifi_off')
                )
              );
            }
            var operators = $('<td>');
            //Status
            if (cell['enabled']){
              content.append(
                $('<td>').append(
                  $('<i>').addClass('material-icons green-text darken-2 tooltipped').attr('data-position', 'top').
                    attr('data-tooltip', texts.get(N.TagEnable)).text('check')
                )
              );
              operators.append(
                $('<a>').attr('href', '#').addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                  attr('data-tooltip', texts.get(N.TagDisable)).attr('onclick', 'disableCell("' + cell['name'] + '")').append(
                    $('<i>').addClass('material-icons').text('do_not_disturb')
                  )
              );
            }else{
              content.append(
                $('<td>').append(
                  $('<i>').addClass('material-icons red-text darken-4 tooltipped').attr('data-position', 'top').
                    attr('data-tooltip', texts.get(N.TagDisable)).text('do_not_disturb')
                )
              );
              operators.append(
                $('<a>').attr('href', '#').addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                  attr('data-tooltip', texts.get(N.TagEnable)).attr('onclick', 'enableCell("' + cell['name'] + '")').append(
                    $('<i>').addClass('material-icons').text('check')
                  )
              );
            }
            operators.append(
              $('<a>').attr('href', '/instance_list.html?pool=' + poolName + '&cell=' +cell['name']).addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagInstance)).append(
                  $('<i>').addClass('material-icons').text('cloud_queue')
                )
            );
            operators.append(
              $('<a>').attr('href', '/cell_detail.html?pool=' + poolName + '&cell=' +cell['name']).addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagDetail)).append(
                  $('<i>').addClass('material-icons').text('settings')
                )
            );
            operators.append(
              $('<a>').attr('href', '#').addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagRemove)).attr('onclick', 'confirmDelete("'+ cell['name'] +'")').append(
                  $('<i>').addClass('material-icons').text('delete')
                )
            );
            operators.append(
              $('<a>').attr('href', '#').addClass('blue-grey-text tooltipped').attr('data-position', 'bottom').
                attr('data-tooltip', texts.get(N.TagMigrate)).attr('onclick', 'confirmMigrate("'+ cell['name'] +'")').append(
                  $('<i>').addClass('material-icons').text('local_shipping')
                )
            );
            content.append(operators);
            container.append(
              table.append(content)
            );
          });
          $('#cell_list').append(container);
          $('.material-tooltip').remove();
          M.Tooltip.init($('.tooltipped'));
        }
      );
    }

    function confirmDelete(name){
      $('#confirm_content').text('Are you sure to remove compute cell ' + name);
      $('#confirm_link').attr('onclick', 'removeCell("' + name + '")');
      var instance = M.Modal.getInstance($('#modal_confirm'));
      instance.open();
    }

    function removeCell(name) {
      $.ajax({
       url:'/compute_pool_cells/' + poolName + '/'+ name,
       type: "DELETE",
       dataType: "json",
       success: function (result) {
           if (0 != result['error_code']) {
               M.toast({html: 'delete cell fail: ' + result['message'], outDuration: 1000});
               return;
           }
           M.toast({html: 'compute cell "' + name + '" removed'});
           setTimeout(refresh, 500);
           N.WriteOperateLog('remove compute cell ' + name);
       }
      });
    }

    function disableCell(cellName) {
      var request = new Object();
      request.enable = false;
      $.ajax({
        url: '/compute_pool_cells/' + poolName + '/' + cellName,
        method: "PUT",
        dataType: "json",
        data: JSON.stringify(request),
        success: function (result) {
            if (0 != result['error_code']) {
                M.toast({html: 'disable cell fail: ' + result['message'], outDuration: 600});
                return;
            }
            M.toast({html: cellName + ' disabled'});
            setTimeout(refresh, 500);
            N.WriteOperateLog('disable compute cell ' + cellName);
        },
        error: function (jqXHR, status, error) {
          M.toast({html: 'request disable cell fail: ' + error, outDuration: 600});
        }
      });
    }

    function enableCell(cellName) {
      var request = new Object();
      request.enable = true;
      $.ajax({
        url: '/compute_pool_cells/' + poolName + '/' + cellName,
        method: "PUT",
        dataType: "json",
        data: JSON.stringify(request),
        success: function (result) {
            if (0 != result['error_code']) {
                M.toast({html: 'enable cell fail: ' + result['message'], outDuration: 600});
                return;
            }
            M.toast({html: cellName + ' enabled'});
            setTimeout(refresh, 500);
            N.WriteOperateLog('enable compute cell ' + cellName);
        },
        error: function (jqXHR, status, error) {
          M.toast({html: 'request enable cell fail: ' + error, outDuration: 600});
        }
      });
    }

    //migrate instance
    function confirmMigrate(sourceCell){
      $('#migrate-confirm-link').attr('onclick', 'migrateInstance("' + sourceCell + '")');
      $.getJSON(
        '/compute_pool_cells/' + poolName,
        function(result){
          if (0 != result['error_code']) {
            M.toast({html: 'query cells fail: ' + result['message']});
            return;
          }
          if (!result['data']){
            M.toast({html: 'no cell available in pool "' + poolName + '"'});
            return;
          }
          if (0 == result['data'].length){
            M.toast({html: 'no cell available in pool "' + poolName + '"'});
            return;
          }
          var options = $('#migrate-target-options').empty();
          var currentAddress = "";
          result['data'].forEach((cell)=>{
            var cellName = cell['name'];
            var displayText = cellName + '('+ cell['address']+')';
            if (cellName == sourceCell){
              currentAddress = displayText;
              return;
            }
            if (!cell['enabled']){
              options.append(
                $('<option>').attr('value', cellName).text(displayText + ' - Disabled').prop('disabled', true)
              );
            }else if(!cell['alive']){
              options.append(
                $('<option>').attr('value', cellName).text(displayText + ' - Lost').prop('disabled', true)
              );
            }else{
              options.append(
                $('<option>').attr('value', cellName).text(displayText)
              );
            }
          });
          M.FormSelect.init($('#migrate-target-options'));
          if (currentAddress){
            $('#migrate-content').text('Migrate all instances from "' + currentAddress + '" to');
          }else{
            $('#migrate-content').text('Migrate all instances from "' + sourceCell + '" to');
          }
          var instance = M.Modal.getInstance($('#migrate-modal'));
          instance.open();
        }
      );
    }

    function migrateInstance(sourceCell){
      var targetCell = $('#migrate-target-options').val();
      if (!targetCell){
        M.toast({html: "invalid target cell"});
        return;
      }
      var request = new Object();
      request.source_pool = poolName;
      request.source_cell = sourceCell;
      request.target_cell = targetCell;
      $.post(
        '/migrations/',
        JSON.stringify(request),
        function(result){
          if (0 != result['error_code']) {
            M.toast({html: 'migrate instance fail: ' + result['message']});
            return;
          }
          if (!result['data']){
            M.toast({html: 'migrate summited, but no data available'});
            return;
          }
          var migration = result['data'];
          M.toast({html: 'try migrate all instance(s) to "'+targetCell+'"'});
        },
        "json"
      );
    }


    var intervalID;
    var refreshInterval = 5*1000;

    function onAutoFreshSwitched(){
      var autoFresh = $('#switch-autofresh').prop( "checked");
      if (autoFresh){
        intervalID = setInterval(refresh, refreshInterval);
        M.toast({html: "Auto Fresh Enabled"});
      }else{
        clearInterval(intervalID);
        intervalID = undefined;
        M.toast({html: "Auto Fresh Disabled"});
      }
    }

    $(function(){
      M.Modal.init($('.modal'));
      var params = parseQueryString();
      if (!params.has('pool')){
        M.toast({html: 'must specify pool name'})
        return;
      }
      poolName = params.get('pool');
      $('#breadcrumb-path').append(
        $('<a>').addClass('breadcrumb').text(poolName).attr('href','#')
      );
      $('#add-button').attr('href', '/add_cell.html?pool=' + poolName);
      loadCells();
      intervalID = setInterval(refresh, refreshInterval);
    });

</script>
</body>
</html>
